<template>
	<u-navbar v-show="!isNew" title="济宁学生资助申请平台" left-icon-color="white" :placeholder="true" title-style="color:white"
		bgColor="#359FE3" :autoBack="true"></u-navbar>
	<u-navbar v-show="isNew" title="济宁学生资助申请平台" left-icon="" :placeholder="true" title-style="color:white"
		bgColor="#359FE3"></u-navbar>
	<uni-card>
		<text class="text-red-600 text-lg font-medium">在阅读政策前，请务必认真核对当前学生信息是否已发生变更！（如学校、年级、班级等）</text>
	</uni-card>

	<view class="content">
		<uni-forms ref="formData" :modelValue="formData" validateTrigger="blur"  label-position="top" :rules="rules">
			<uni-forms-item required label="学生姓名" name="fullname">
				<uni-easyinput type="text" confirmType="next" v-model="formData.fullname" />
			</uni-forms-item>
			<uni-forms-item required label="身份证号" name="idnumber">
				<uni-easyinput type="idcard" confirmType="next" v-model="formData.idnumber" />
			</uni-forms-item>
			<uni-forms-item required label="民族" name="nation">
				<z-picker @selectVal="selectNation" placeholder="请选择民族" parent="none" :itemList="nationList" :defaultValue="formData.nation"  itemKey="nationName" itemLabel="nationName"></z-picker>
			</uni-forms-item>
			<uni-forms-item label="联系电话" name="phone">
				<uni-easyinput type="number" confirmType="next" v-model="formData.phone" />
			</uni-forms-item>

			<uni-forms-item required label="出生日期" name="birthday">
				<u-datetime-picker :show="showDatePicker" :minDate="946656000000" :closeOnClickOverlay="true" v-model="formData.birthday"
					@close="showDatePicker=false" @confirm="confirmBirth" @cancel="showDatePicker=false"
					mode="date"></u-datetime-picker>
				<u-button class="justify-start" @click="showDatePicker = true">{{formData.birthday}}</u-button>
			</uni-forms-item>
			<uni-forms-item required label="入学年月" name="inSchoolTime">
				<u-datetime-picker :show="showInSchoolDate" :minDate="946656000000" :closeOnClickOverlay="true" v-model="formData.inSchoolTime"
					@close="showInSchoolDate=false" @confirm="confirmInSchool" @cancel="showInSchoolDate=false"
					mode="year-month"></u-datetime-picker>
				<u-button class="justify-start" @click="showInSchoolDate = true">{{formData.inSchoolTime}}</u-button>
			</uni-forms-item>
			<uni-forms-item required label="归属教育局" :label-width="250" name="regionId">
				<z-picker @selectVal="selectRegion" placeholder="请选择教育局" parent="none" itemLabel="name" itemKey="name" :defaultValue="formData.regionId" :itemList="regionList"></z-picker>
			</uni-forms-item>
			<uni-forms-item required label="在读学校" name="school">
				<z-page-picker @selectVal="selectSchool"  @toast="showTip('请先选择教育局')" :parent="formData.regionId" placeholder="请选择学校" itemLabel="name" itemKey="name"
					:defaultValue="formData.school" :itemList="schoolList"></z-page-picker>
			</uni-forms-item>
			<uni-forms-item required label="当前年级" name="curGrade">
				<z-picker @selectVal="selectGrade" @toast="showTip('请先选择学校')" :parent="formData.school" placeholder="请选择年级" itemLabel="name" itemKey="name" :defaultValue="formData.curGrade" :itemList="gradeList"></z-picker>
			</uni-forms-item>
			<uni-forms-item required label="当前班级" name="curClass">
				<z-picker @selectVal="selectClass" @toast="showTip('请先选择年级')" :parent="formData.curGrade" placeholder="请选择班级" itemLabel="name" itemKey="name" :defaultValue="formData.curClass" :itemList="classList"></z-picker>
			</uni-forms-item>
			
			<uni-forms-item required label="家庭住址" name="homeAddress">
				<u--textarea v-model="formData.homeAddress" placeholder="请输入家庭住址" ></u--textarea>
			</uni-forms-item>
			
		</uni-forms>
		<button size="default" v-if="!isNew" type="primary" @click="submitStudent">确认信息无误</button>
	</view>
</template>

<script>
	import {
		saveParentAndStudent,
		saveStudentInfo,
		orgList,
		queryNationList,
		queryStudent,
		dictList
	} from '@/api/login.js'
	import dayjs from 'dayjs'
	import {
		isIdCardNo
	} from '@/utils/common/validation-methods.js'
	import lodashFull from '@/uni_modules/iRainna-lodash/js_sdk/js/lodash.full.min.js'
	const {
		isNil
	} = lodashFull()
	dayjs.locale('zh-cn');
	
	export default {
		data() {
			return {
				isNew: false,
				showDatePicker: false,
				showInSchoolDate: false,
				nationList:[],
				regionList: [],
				schoolList: [],
				gradeList: [],
				classList: [],
				formData: {
					id:'',
					fullname: '',
					phone: '',
					idnumber: '',
					birthday: '',
					regionId: '',
					school: '',
					curGrade: '',
					curClass: '',
					inSchoolTime: '',
					nation: '',
					homeAddress: '',
					period: '',
					defaultFlag: 1
				},
				rules: {
					fullname: {
						rules: [{
							required: true,
							errorMessage: '请填写姓名！'
						}]
					},

					idnumber: {
						rules: [{
								required: true,
								errorMessage: '请填写身份证号！'
							},
							{
								validateFunction: function(rule, value, data, callback) {
									return isIdCardNo(value)
								},
								errorMessage: '身份证号格式有误！'
							}
						]
					},
					nation: {
						rules: [{
								required: true,
								errorMessage: '请选择民族！'
							}
						]
					},
					regionId: {
						rules: [{
								required: true,
								errorMessage: '请选择教育局！'
							}
						]
					},
					school: {
						rules: [{
								required: true,
								errorMessage: '请选择学校！'
							}
						]
					},
					curGrade: {
						rules: [{
								required: true,
								errorMessage: '请选择年级！'
							}
						]
					},
					curClass: {
						rules: [{
								required: true,
								errorMessage: '请选择班级！'
							}
						]
					},
					birthday: {
						rules: [{
							required: true,
							errorMessage: '请选择学生生日！'
						}]
					},
					inSchoolTime: {
						rules: [{
							required: true,
							errorMessage: '请选择入学年月！'
						}]
					},
					homeAddress: {
						rules: [{
							required: true,
							errorMessage: '请填写家庭住址！'
						}]
					},
					
				}
			}
		},
		onLoad(option) {
			this.isNew = JSON.parse(option.isNew)
			if(!isNil(option.studentId)){
				this.formData.id = option.studentId
			}
			const parentInfo = uni.getStorageSync("parentInfo")
			this.setDefaultValue()
		},
		watch: {
			'formData.idnumber': {
				handler(newVal) {
					if(newVal!=undefined && newVal.length==18){
						let idnumber = newVal.toString()
						this.formData.birthday = dayjs(idnumber.substring(6,14), 'YYYYMMDD').format('YYYY-MM-DD')
					}
					
				}
			}
		},
		methods: {
			back() {
				uni.navigateBack({
					delta: 1
				});
			},
			async confirmBirth(e) {
				this.showDatePicker = false;
				const timeFormat = uni.$u.timeFormat;
				let timeValue = await timeFormat(e.value, 'yyyy-mm-dd');
				this.formData.birthday = timeValue;
			},
			async confirmInSchool(e) {
				this.showInSchoolDate = false;
				const timeFormat = uni.$u.timeFormat;
				let timeValue = await timeFormat(e.value, 'yyyy-mm');
				this.formData.inSchoolTime = timeValue;
			},
			async selectRegion(e) {
				console.log('selectRegion');
				if(e){
					this.formData.regionId = e.name
					this.formData.school =''
					this.formData.curGrade =''
					this.formData.curClass =''
				}
					
				// orgList("4", e.id).then(res => {
				// 	this.schoolList = [res.orgList]
				// })
				
				if(this.regionList && this.regionList.length>0) return;
				const region_res = await orgList('3')
				if (region_res.success) {
					this.regionList = [region_res.orgList]
				}
			},
			selectSchool(e) {
				console.log('selectSchool');
				if(e){
					this.formData.school = e.name
					this.formData.curGrade =''
					this.formData.curClass =''
				}
				
				
				orgList("4", {
						"stuRegion":this.formData.regionId,
				}).then(res => {
					this.schoolList = [res.orgList]
					console.log('this.schoolList',this.schoolList)
				})
				
				// orgList("5", e.id).then(res => {
				// 	this.gradeList = [res.orgList]
				// })
			},
			selectGrade(e) {
				console.log('selectGrade');
				if(e){
					this.formData.curGrade = e.name
					this.formData.period = e.master
					this.formData.curClass =''
				}
				
				
				orgList("5",{
						"stuRegion":this.formData.regionId,
						"stuSchool":this.formData.school
				}).then(res => {
					this.gradeList = [res.orgList]
				})
				
				// orgList("6", e.id).then(res => {
				// 	this.classList = [res.orgList]
				// })
			},
			selectClass(e) {
				console.log('selectClass');
				if(e){
					this.formData.curClass = e.name
				}
			
				
				orgList("6", {
						"stuRegion":this.formData.regionId,
						"stuSchool":this.formData.school,
						"stuGrade":this.formData.curGrade
				}).then(res => {
					this.classList = [res.orgList]
				})
			},
			async selectNation(e){
				if(e){
					this.formData.nation = e.nationName
				}	
			},
			showTip(text){
				console.log(text);
				uni.showModal({
					title: '提示',
					content: text,
					showCancel:false
				});
			},
			async setDefaultValue(){
				const res3 = await queryStudent(this.formData.id)
				if(res3.success){
					this.formData = res3.student
				}
				const region_res = await orgList('3')
				if (region_res.success) {
					this.regionList = [region_res.orgList]
				}
				if(!(isNil(this.formData.school)||this.formData.school=='')){
					const grade_res = await orgList('5',this.formData.school)
					if (grade_res.success) {
						this.gradeList = [grade_res.orgList]
					}
				}
				// const school_res = await orgList('4',this.formData.regionId)
				// if (school_res.success) {
				// 	this.schoolList = [school_res.orgList]
				// }
				// const grade_res = await orgList('5',this.formData.school)
				// if (grade_res.success) {
				// 	this.gradeList = [grade_res.orgList]
				// }
				// const class_res = await orgList('6',this.formData.curGrade)
				// if (class_res.success) {
				// 	this.classList = [class_res.orgList]
				// }
				const res2 = await queryNationList()
				if (res2.success) {
					this.nationList = [res2.nationList]
				}
				
			},
			submitStudent() {
				this.$refs.formData.validate().then(res => {
					console.log(this.formData)
					saveStudentInfo(this.formData).then(res => {
						if (res.success) {
							uni.showToast({
								title: res.msg,
								complete: () => {
									uni.redirectTo({
										url:'/pages/zizhuzhengce/zizhuzhengce'
									})
								}
							})
						}
					})
				}).catch(err => {
					console.log('表单错误信息：', err);
				})
			
			}
		}
	}
</script>

<style>
	.nav-title {
		font-size: 40rpx;
		width: 100%;
		text-align: center;
	}
	.uni-forms-item{
		margin: 60rpx auto;
		font-size: 30rpx;
	}
	.content {
		padding: 40rpx;
	}

	.justify-start {
		justify-content: start !important;
	}
</style>